package cn.kgc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class NewsDao1 {
	//查询特定标题的新闻信息
	public void getNewsByTitle(String title){
		Connection connection = null;
		Statement stmt = null;
		ResultSet rs = null;
		
		try {
			//加载不同数据库厂商提供的驱动
			Class.forName("com.mysql.jdbc.Driver"); 
			//查询来说
			//（1）铺路（获取连接connection）
			String url = "jdbc:mysql://localhost:3306/kgcnews";
			connection = DriverManager.getConnection(url, "root", "1234");
			//（2）下圣旨（sql命令）
			String sql = "SELECT id,title FROM news_detail where title='"+title+"'";
			System.out.println(sql);
			//（3）找一个小太监帮皇上执行圣旨（statement/PreparedStatement）
			stmt = connection.createStatement();
			//（4）拉回西瓜（返回结果集Resultset）
			rs = stmt.executeQuery(sql);
			while(rs.next()){
				/*int id = rs.getInt(1);
				String title = rs.getString(2);*/
				int id = rs.getInt("id");
				String newsTitle = rs.getString("title");
				System.out.println(id+"\t"+newsTitle);
			}			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{			
			try {
				//（5）关闭城门（释放资源）
				rs.close();
				stmt.close();
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		 
	}
	
	public static void main(String[] args) {
		NewsDao1 dao = new NewsDao1();
//		dao.getNewsByTitle("Java Web开课啦"); 
		dao.getNewsByTitle("Java Web开课啦' or '1'='1");
	}
}
